// pages/shopping/uploadDocuments/uploadDocuments.js
var app = getApp();
var util = require("../../../utils/util.js");
var idCrad1 = app.globalData._network_path + 'id5.png';
var idCrad2 = app.globalData._network_path + 'id6.png';
let front_idcard_pic1 = '';//身份证正面照片半路径
let back_idcard_pic1 = '';//身份证反面照片半路径
let business_license_pic1 = '';//营业执照照片半路径
var check_type = '';//审核方式
let cutImg =  '';//需要裁剪的图片

Page({

  /**
   * 页面的初始数据
   */
  data: {
    idCrad1: idCrad1,//摄像背景1
    idCrad2: idCrad2,//摄像背景2
    types: 1, //认证类型 1 用户认证 2 企业认证 3政事认证
    isDisable: true, //按钮状态
    front_idcard_pic: '', //身份证正面照片
    back_idcard_pic: '', //身份证反面照片
    business_license_pic: '', //营业执照照片/单位附件
    authInfo: {},//认证信息
    sub_loading: false,//提交按钮动画
    sub_txet: '下一步',//提交按钮文字说明
    flag: false,
    readOnly: true,
    check_type: '',//审核方式
    user_id:'',
    showCamer: false,//知否显示定义相机
    imgWay: 1,//图片类型(身份证正反面)
    imgwidth: 0,//身份证宽度
    imgheight: 0,//身份证高度
    isShow: false,//是否打开中间页面(选择相机还是相册)
    is_rotate1: false,//默认不需要旋转(仅仅是展示)1正面
    is_rotate2: false,//默认不需要旋转(仅仅是展示)2反面
    cut_show: false,//是否显示裁剪图片
    cut_width: 260,//宽度
    cut_height: 260,//高度
    ensureImg: '',//预览路径
    nextTwo: '',//是否打开预览

    cropperOptions: {
      hidden: true,
      src: '',
      mode: '',
      sizeType: []
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    if (util.isExitsVariable(options.types)) {
      that.setData({
        types: options.types,
      });
    }
    that.setData({
      user_id: options.user_id,
      imgwidth: wx.getSystemInfoSync().windowWidth * 0.8,//宽 身份证宽高比为1:1.58
      imgheight: wx.getSystemInfoSync().windowWidth * 0.8 * 1.58,
    })
    that.getAuthInfo();

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */


  // 上传身份证正面
  uploadPimg1: function () {
    var that = this;
    //修改导航条颜色和背景 2为黑色 并且关闭中间页
    that.oldColor(2);
    that.setData({
      isShow: false,
    })
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片  
        //选取图片给裁剪使用
        var tempFilePaths = res.tempFilePaths;
        console.log('tempFiles', res.tempFiles);
        front_idcard_pic1 = '';
        cutImg = tempFilePaths;//需要裁剪的图片
        that.setData({
          cut_show: true,//加载图片裁剪功能
          cropperOptions: {
            hidden: false,
            src: tempFilePaths[0],
            mode: 'rectangle',
            sizeType: ['original', 'compressed'], //'original'(default) | 'compressed'
            maxLength: 1000, //默认2000，允许最大长宽，避免分辨率过大导致崩溃
          }
        })
      }
    })
  },

  // 上传身份证反面
  uploadPimg2: function () {
    var that = this;
    //修改导航条颜色和背景 2为黑色 并且关闭中间页
    that.oldColor(2);
    that.setData({
      isShow: false
    })
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片  
        var tempFilePaths = res.tempFilePaths;
        back_idcard_pic1 = '';
        cutImg = tempFilePaths,//需要裁剪的图片
        that.setData({
          cut_show: true,//加载图片裁剪功能
          cropperOptions: {
            hidden: false,
            src: tempFilePaths[0],
            mode: 'rectangle',
            sizeType: ['original', 'compressed'], //'original'(default) | 'compressed'
            maxLength: 1000, //默认2000，允许最大长宽，避免分辨率过大导致崩溃
          }
        })
      }
    })
  },

  // 上传营业执照
  uploadCimg: function () {
    var that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片  
        business_license_pic1 = '';
        var tempFilePaths = res.tempFilePaths;
        that.upImg(tempFilePaths[0], 0)
        //var url = that.data.url;
        setTimeout(function () {
          that.setData({
            business_license_pic: tempFilePaths          
          })
        }, 500);
      }
    })
  },

  // 图片上传
  upImg: function (tempFilePaths, type) {
    var that = this;
    console.log(type, "ttype")
    wx.showLoading({
      title: '上传图片中',
    })
    wx.uploadFile({
      url: app.globalData._url + 'Common/Common/upload',
      filePath: tempFilePaths,
      name: 'file',
      success: function (res) {
        wx.hideLoading();
        var res = JSON.parse(res.data);
        if (res.code == 1000) {
          if (type == 0) {
            business_license_pic1 = res.data.url;
            if (business_license_pic1 != '') {
              that.setData({
                isDisable: false
              })
            }
          } else if (type == 1) {
            front_idcard_pic1 = res.data.url;
            if (front_idcard_pic1 != '' && back_idcard_pic1 != '') {
              that.setData({
                isDisable: false
              })
            }
          } else if (type == 2) {
            back_idcard_pic1 = res.data.url;
            if (front_idcard_pic1 != '' && back_idcard_pic1 != '') {
              that.setData({
                isDisable: false
              })
            }
          }
        } else {
          app.showToast("上传图片失败");
        }
        //do something
      }
    })
  },

  // 上一步
  prevstep() {
    wx.navigateTo({
      url: '../../shopping/realName/realName',
    })
  },

  // 下一步
  nextstep() {
    var that = this;
    if (that.data.flag) {
      return false;
    }
    if (that.data.isDisable) {
      return false;
    }
    that.setData({
      sub_loading: true,//提交按钮动画
      sub_txet: '正在验证中~~',//提交按钮文字说明
      flag: true,
      isDisable: true,
    })
    var da_ta = { 
      'front_idcard_pic': front_idcard_pic1, 
      "back_idcard_pic": back_idcard_pic1, 
      'user_id': that.data.user_id, 
      'businesspic': business_license_pic1,
       'auth_type': that.data.types 
  }
    // ajax请求
    app.ajax({
      url: 'Engineer/Realname/step2',
      data: da_ta,
      success: function (res) {
        that.setData({
          sub_txet: '下一步',//提交按钮文字说明
          //flag: false,
          sub_loading: false
        })

        if (res.data.code == 1000 || res.data.code == 1001) {
          app.showToast(res.data.message);
          that.setData({
            sub_txet: '下一步',//提交按钮文字说明
          })
          setTimeout(function () {
            wx.navigateTo({
              url: '../faceRecognition/faceRecognition?user_id=' + that.data.user_id
            })
          }, 2000)
        } else if (res.data.code == 1100) {
          that.setData({
            sub_txet: '提交',//提交按钮文字说明
          })
          setTimeout(function () {
            wx.navigateTo({
              url: '../auditResult/auditResult?result=1&user_id='+that.data.user_id
            })
          }, 2000)
        } else if (res.data.code == 1200) {
          that.setData({
            sub_txet: '提交',//提交按钮文字说明
          })
          setTimeout(function () {
            wx.navigateTo({
              url: '../auditResult/auditResult?result=2&user_id=' + that.data.user_id
            })
          }, 2000)
        } else {
          that.setData({
            isDisable: false,
            flag: false,
          })
          app.showToast(res.data.message);
        }

      }
    })

  },
  //获取用户认证信息
  //  
  getAuthInfo() {
    var that = this;
    app.ajax({
      url: "Engineer/Realname/getAuthInfo",
      data: { 'user_id': that.data.user_id},
      success: function (res) {
        if (res.data.code == 1000) {
          var isDisable = true;
          if (util.isExitsVariable(res.data.data.front_idcard_pic) && util.isExitsVariable(res.data.data.back_idcard_pic)) {
            isDisable = false;
          }
          //是否可编辑
          var readOnly = true;
          if (res.data.data.status == -2 || res.data.data.status == 3 || res.data.data.status == -4) {
            readOnly = false;
          }
          var sub_txet = '提交';
          if (res.data.data.cur_system_check_type == 2) {
            sub_txet = '下一步';
          }
          front_idcard_pic1 = res.data.data.front_idcard_pic;
          back_idcard_pic1 = res.data.data.back_idcard_pic;
          that.setData({
            authInfo: res.data.data,
            front_idcard_pic: res.data.data.front_idcard_pic_all,
            back_idcard_pic: res.data.data.back_idcard_pic_all,
            business_license_pic: res.data.data.business_license_pic_all,
            business_license_pic1: res.data.data.business_license_pic || '',
            isDisable: isDisable,
            readOnly: readOnly,
            check_type: res.data.data.cur_system_check_type,
            sub_txet: sub_txet,
            types: res.data.data.auth_type
          })
        }
      }
    })
  },
  //打开选择相机还是相册
  openAbout(e) {
    var that = this;
    //关闭中间页面 打开自定义照相机
    that.setData({
      showCamer: true,
      isShow: false,
    })
    //修改导航条颜色和背景 2为黑色
    that.oldColor(2);
  },
  //打开相机
  cameraOpen(e) {
    var that = this;
    var ways = e.currentTarget.dataset.imgway;
    //打开中间页面 并设置是正面照还是反面照
    that.setData({
      isShow: true,
      imgWay: ways,
    })
  },
  //关闭相机
  cameraClose() {
    var that = this;
    that.oldColor(1);
    that.setData({
      showCamer: false
    })
  },
  //照相
  takePhotoFun() {
    var that = this;
    var ctx = wx.createCameraContext();
    ctx.takePhoto({
      quality: 'high',
      success: (res) => {
        if (that.data.imgWay == 1) {
          front_idcard_pic1 = '';
          wx.getSystemInfo({
            success(res) {
              if (res.system.substring(3, 0) === 'iOS' || res.system.substring(3, 0) === 'ios') {
                that.setData({
                  is_rotate1: false//不需要旋转 正面
                })
              } else {
                that.setData({
                  is_rotate1: true//需要旋转 正面
                })
              }
            }
          })
          that.upImg(res.tempImagePath, 1);
          setTimeout(function () {
            that.setData({
              front_idcard_pic: res.tempImagePath,
              showCamer: false
            })
          }, 500);
        } else if (that.data.imgWay == 2) {
          business_license_pic1 = '';
          wx.getSystemInfo({
            success(res) {
              if (res.system.substring(3, 0) === 'iOS' || res.system.substring(3, 0) === 'ios') {
                that.setData({
                  is_rotate2: false//不需要旋转 反面
                })
              } else {
                that.setData({
                  is_rotate2: true//需要旋转 反面
                })
              }
            }
          })
          that.upImg(res.tempImagePath, 2)
          setTimeout(function () {
            that.setData({
              back_idcard_pic: res.tempImagePath,
              showCamer: false
            })
          }, 500);
        } else {
          app.showToast('请重新选择');
        }
        that.oldColor(1);
      },
      error: (res) => {
        that.setData({
          front_idcard_pic: '',
          showCamer: false
        })
        that.oldColor(1);
      }
    })
  },
  //修改导航条颜色和背景 (1是原来颜色 2全黑色)
  oldColor(opens) {
    if (opens == 2) {
      wx.setNavigationBarColor({
        frontColor: '#000000',
        backgroundColor: '#000000',
        animation: {
          duration: 400,
          timingFunc: 'easeIn'
        }
      })
    } else {
      wx.setNavigationBarColor({
        frontColor: '#ffffff',
        backgroundColor: '#6ca9ff',
        animation: {
          duration: 400,
          timingFunc: 'easeIn'
        }
      })
    }
  },
  //相机错误事件
  errorFun(e) {
    console.log(e.detail);
    app.showToast('您未打开摄像头权限');
  },
  //摄像头在非正常终止时触发，如退出后台等情况
  stopFun(e) {
    // app.showToast('关闭摄像头');
    console.log('关闭摄像头', e.detail);
  },
  //图片加载错误
  cuowu(e) {
    console.log('图片加载错误', e.detail);
  },
  // 关闭中间页面
  closeShoot() {
    var that = this;
    that.setData({
      isShow: false
    })
  },
  //取消裁剪
  closeFun() {
    var that = this;
    that.setData({
      cut_show: false,
    })
    //修改导航条颜色和背景 1原色
    that.oldColor(1);
  },
  //重新选取裁剪
  reelectFun() {
    var that = this;
    if (that.data.imgWay == 1) {
      that.uploadPimg1();//重新选取正面照
    } else {
      that.uploadPimg2();
    }
  },
  //初始化图片裁剪--------  以下插件---------------
  cropperload(e) {
    console.log("cropper初始化完成");
  },
  //图片加载状态
  loadimage(e) {
    console.log("图片加载完成", e.detail);
    wx.hideLoading();
    //重置图片角度、缩放、位置
    //this.cropper.imgReset();
  },
  //开始裁剪
  clickcut(e) {
    var that = this;
    //打开预览
    that.setData({
      ensureImg: e.detail.res,//预览
      nextTwo: true,//打开预览
      cut_show: false,
    })
  },
  //取消重新裁剪
  anewFun() {
    var that = this;
    that.setData({
      ensureImg: '',//预览
      nextTwo: false,//打开预览
      cut_show: true,
    })
  },
  //确定 选取图片
  ascertainFun() {
    var that = this;
    var preview = that.data.ensureImg;
    //裁剪的图片不能为空
    if (preview == '') {
      app.showToast('请重新裁剪图片');
      return false;
    }
    //修改导航条颜色和背景 1为原色
    that.oldColor(1);
    if (that.data.imgWay == 1) {
      //正面
      that.upImg(preview, 1)
      setTimeout(function () {
        that.setData({
          nextTwo: false,
          front_idcard_pic: preview,
          is_rotate1: false//不需要旋转--正面
        })
      }, 500);
    } else {
      //背面
      that.upImg(preview, 2)
      setTimeout(function () {
        that.setData({
          nextTwo: false,
          back_idcard_pic: preview,
          is_rotate2: false//不需要旋转--反面
        })
      }, 500);
    }
  }
})